package com.example.wifi_direct.ui.main.fragment

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import com.example.wifi_direct.R
import com.example.wifi_direct.ui.main.NewsApplication
import com.example.wifi_direct.ui.main.act.SearchActivity
import com.google.android.material.tabs.TabLayout

class HomeFragment:  Fragment(){

    // 类型,shehui(社会),guonei(国内),guoji(国际),yule(娱乐),tiyu(体育)junshi(军事),keji(科技),caijing(财经),shishang(时尚)

    private val newsTypeList = listOf("shehui","guonei","guoji","yule","keji")
    private val titleList = listOf("社会","国内","国际","娱乐","科技")
    // 初始化一个空fragment列表
    private val fragmentlist = ArrayList<NewsFragment>()

    private lateinit var editText: EditText
    private lateinit var tabLayout: TabLayout
    private lateinit var viewPager: ViewPager

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_home,container,false)
        tabLayout = view.findViewById(R.id.news_tab_layout)
        viewPager = view.findViewById(R.id.news_view_pager)
        editText = view.findViewById(R.id.home_edit_text)
        return view
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)


        for(newsType in newsTypeList) {
            fragmentlist.add(NewsFragment(newsType))
        }
        viewPager.offscreenPageLimit = titleList.size
        viewPager.adapter = MyAdapter(childFragmentManager)

        // 实现viewPager左右滑动与tabLayout这个标签选择器的联动
        tabLayout.setupWithViewPager(viewPager)



        // 设置home页面的搜索框 不可编辑 使得退出和一开始无法弹出输入
        editText.keyListener = null
        // 设置home页面的搜索框的点击事件: 打开SearchActivity这个页面，即搜索页面
        editText.setOnClickListener {
            val intent = Intent(NewsApplication.context, SearchActivity::class.java)
            startActivity(intent)
        }

    }

    inner class MyAdapter(fm: FragmentManager): FragmentPagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT){
        override fun getCount(): Int {
            return  fragmentlist.size
        }

        override fun getItem(position: Int): Fragment {
            return fragmentlist[position]
        }

        override fun getPageTitle(position: Int): CharSequence {
            return titleList[position]
        }

    }
}